<template>
  <div class="donation-management">
    <div class="page-header">
      <h1 class="page-title">爱心捐募管理</h1>
      <el-button type="primary" class="add-btn" @click="handleAddDonation">
        <el-icon><Plus /></el-icon>
        新增捐赠项目
      </el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-item">
              <div class="statistic-title">总捐赠金额</div>
              <div class="statistic-value primary">¥{{ totalAmount }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-item">
              <div class="statistic-title">捐赠次数</div>
              <div class="statistic-value success">{{ donationCount }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-item">
              <div class="statistic-title">本月捐赠</div>
              <div class="statistic-value warning">¥{{ monthlyAmount }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-item">
              <div class="statistic-title">进行中项目</div>
              <div class="statistic-value info">{{ activeProjects }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="捐赠时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="date-picker"
          />
        </el-form-item>
        <el-form-item label="捐赠状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" class="status-select">
            <el-option label="全部" value="" />
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" class="reset-btn">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 捐赠列表 -->
    <el-table 
      :data="donationList" 
      style="width: 100%" 
      v-loading="loading"
      class="donation-table"
      :header-cell-style="{background:'#f5f7fa'}"
      border
    >
      <el-table-column prop="project_name" label="项目名称" min-width="180"/>
      <el-table-column prop="target_amount" label="目标金额" width="120">
        <template #default="scope">
          <span class="amount">¥{{ scope.row.target_amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="current_amount" label="当前金额" width="120">
        <template #default="scope">
          <span class="amount">¥{{ scope.row.current_amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="donor_count" label="捐赠人数" width="100" align="center"/>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)" effect="light">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="start_date" label="开始时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.start_date) }}
        </template>
      </el-table-column>
      <el-table-column prop="end_date" label="结束时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.end_date) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" plain @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button size="small" type="success" plain @click="handleDetail(scope.row)">
            <el-icon><View /></el-icon>详情
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            plain
            @click="handleDelete(scope.row)"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      class="custom-dialog"
    >
      <el-form :model="donationForm" label-width="100px" class="donation-form">
        <el-form-item label="项目名称">
          <el-input v-model="donationForm.project_name" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="目标金额">
          <el-input-number v-model="donationForm.target_amount" :min="0" placeholder="请输入目标金额" class="amount-input"/>
        </el-form-item>
        <el-form-item label="项目时间">
          <el-date-picker
            v-model="donationForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="date-picker"
          />
        </el-form-item>
        <el-form-item label="项目状态">
          <el-select v-model="donationForm.status" placeholder="请选择状态" class="status-select">
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="捐款记录详情"
      v-model="detailDialogVisible"
      width="70%"
      class="custom-dialog"
    >
      <el-table 
        :data="recordsList" 
        v-loading="recordsLoading"
        class="records-table"
        :header-cell-style="{background:'#f5f7fa'}"
        border
      >
        <el-table-column prop="donorName" label="捐赠人" min-width="120"/>
        <el-table-column prop="amount" label="捐赠金额" width="120">
          <template #default="scope">
            <span class="amount">¥{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="留言" min-width="200"/>
        <el-table-column prop="createTime" label="捐赠时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="recordsTotal"
          :page-size="recordsPageSize"
          :current-page="recordsCurrentPage"
          @size-change="handleRecordsSizeChange"
          @current-change="handleRecordsCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, View, Search, Refresh } from '@element-plus/icons-vue'

export default {
  name: 'DonationManagement',
  components: {
    Plus,
    Edit, 
    Delete,
    View,
    Search,
    Refresh
  },
  data() {
    return {
      // 统计数据
      totalAmount: 0,
      donationCount: 0,
      monthlyAmount: 0,
      activeProjects: 0,

      // 搜索表单
      searchForm: {
        dateRange: [],
        status: ''
      },

      // 表格数据
      loading: false,
      donationList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,

      // 对话框数据
      dialogVisible: false,
      dialogTitle: '新增捐赠项目',
      donationForm: {
        project_name: '',
        target_amount: 0,
        dateRange: [],
        status: 'active'
      },
      isEdit: false,
      editId: null,

      // 详情对话框数据
      detailDialogVisible: false,
      recordsLoading: false,
      recordsList: [],
      recordsTotal: 0,
      recordsPageSize: 10,
      recordsCurrentPage: 1,
      currentProjectId: null
    }
  },
  methods: {
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 格式化日期时间
    formatDateTime(datetime) {
      if (!datetime) return '';
      const d = new Date(datetime);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hour = String(d.getHours()).padStart(2, '0');
      const minute = String(d.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

    // 搜索相关方法
    handleSearch() {
      this.currentPage = 1
      this.fetchDonationList()
    },
    resetSearch() {
      this.searchForm = {
        dateRange: [],
        status: ''
      }
      this.currentPage = 1
      this.fetchDonationList()
    },

    // 表格操作方法
    handleAddDonation() {
      this.isEdit = false
      this.dialogTitle = '新增捐赠项目'
      this.donationForm = {
        project_name: '',
        target_amount: 0,
        dateRange: [],
        status: 'active'
      }
      this.dialogVisible = true
    },
    async handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑捐赠项目'
      this.donationForm = {
        project_name: row.project_name,
        target_amount: row.target_amount,
        dateRange: [row.start_date, row.end_date],
        status: row.status
      }
      this.dialogVisible = true
    },
    async handleDetail(row) {
      this.currentProjectId = row.id
      this.detailDialogVisible = true
      this.recordsCurrentPage = 1
      this.fetchProjectRecords()
    },
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确认删除该捐赠项目吗？', '提示', {
          type: 'warning'
        })
        await request.delete(`/donation/${row.id}`)
        ElMessage.success('删除成功')
        this.fetchDonationList()
      } catch (error) {
        console.error('删除失败:', error)
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        const params = {
          project_name: this.donationForm.project_name,
          target_amount: this.donationForm.target_amount,
          start_date: this.donationForm.dateRange[0],
          end_date: this.donationForm.dateRange[1],
          status: this.donationForm.status
        }

        if (this.isEdit) {
          await request.put(`/donation/update`, {
            ...params,
            id: this.editId
          })
          ElMessage.success('编辑成功')
        } else {
          await request.post('/donation/add', params)
          ElMessage.success('新增成功')
        }

        this.dialogVisible = false
        this.fetchDonationList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      }
    },

    // 分页方法
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchDonationList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchDonationList()
    },

    // 详情记录分页方法
    handleRecordsSizeChange(val) {
      this.recordsPageSize = val
      this.fetchProjectRecords()
    },
    handleRecordsCurrentChange(val) {
      this.recordsCurrentPage = val
      this.fetchProjectRecords()
    },

    // 状态处理方法
    getStatusType(status) {
      const statusMap = {
        active: 'success',
        completed: 'info',
        closed: 'danger'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        active: '进行中',
        completed: '已完成',
        closed: '已关闭'
      }
      return statusMap[status] || status
    },

    // 获取数据方法
    async fetchDonationList() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: this.searchForm.status
        }
        
        // 处理日期范围
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }

        const { data } = await request.get('/donation/list', { params })
        this.donationList = data.list
        this.total = data.total
      } catch (error) {
        console.error('获取捐赠列表失败:', error)
        ElMessage.error('获取列表失败')
      } finally {
        this.loading = false
      }
    },

    // 获取项目捐款记录
    async fetchProjectRecords() {
      this.recordsLoading = true
      try {
        const params = {
          pageNum: this.recordsCurrentPage,
          pageSize: this.recordsPageSize
        }
        const { data } = await request.get(`donation/records/project/${this.currentProjectId}`, { params })
        this.recordsList = data.list
        this.recordsTotal = data.total
      } catch (error) {
        console.error('获取捐款记录失败:', error)
        ElMessage.error('获取捐款记录失败')
      } finally {
        this.recordsLoading = false
      }
    },

    // 获取统计数据
    async fetchStatistics() {
      try {
        const { data } = await request.get('/donation/statistics')
        this.totalAmount = data.totalAmount
        this.donationCount = data.donationCount
        this.monthlyAmount = data.monthlyAmount
        this.activeProjects = data.activeProjects
      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.error('获取统计数据失败')
      }
    }
  },
  created() {
    this.fetchDonationList()
    this.fetchStatistics()
  }
}
</script>

<style scoped>
.donation-management {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
  font-weight: 600;
}

.add-btn {
  padding: 12px 20px;
}

.statistics-cards {
  margin-bottom: 24px;
}

.statistic-card {
  transition: all 0.3s;
}

.statistic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.statistic-item {
  text-align: center;
  padding: 20px 0;
}

.statistic-title {
  font-size: 16px;
  color: #909399;
  margin-bottom: 12px;
}

.statistic-value {
  font-size: 28px;
  font-weight: 600;
  line-height: 1;
}

.statistic-value.primary {
  color: #409EFF;
}

.statistic-value.success {
  color: #67C23A;
}

.statistic-value.warning {
  color: #E6A23C;
}

.statistic-value.info {
  color: #909399;
}

.search-section {
  margin-bottom: 24px;
  padding: 24px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.date-picker {
  width: 360px;
}

.status-select {
  width: 180px;
}

.search-btn,
.reset-btn {
  padding: 12px 20px;
}

.donation-table {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
}

.amount {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.custom-dialog {
  border-radius: 8px;
}

.donation-form {
  padding: 20px;
}

.amount-input {
  width: 180px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

.records-table {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .date-picker {
    width: 300px;
  }
  
  .status-select {
    width: 150px;
  }
}

@media screen and (max-width: 768px) {
  .donation-management {
    padding: 16px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .statistic-value {
    font-size: 24px;
  }
  
  .search-section {
    padding: 16px;
  }
  
  .date-picker {
    width: 100%;
  }
  
  .status-select {
    width: 100%;
  }
}
</style> 